package com.xgh.boss;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName DeathLock
 * @Description
 * @Author xinggh
 * @Date 2020/8/13 23:03
 * @Version 1.0
 **/
public class DeathLock2 {

    public static void main(String[] args) {
        ReentrantLock a = new ReentrantLock();
        ReentrantLock b = new ReentrantLock();


        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    a.tryLock(5, TimeUnit.SECONDS);
                    System.out.println(Thread.currentThread().getName() + "尝试获取a 成功");
                    System.out.println(Thread.currentThread().getName() + "尝试获取b ...");
                    b.tryLock(5, TimeUnit.SECONDS);
                    System.out.println(Thread.currentThread().getName() + "尝试获取b 成功");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    if (a.isHeldByCurrentThread()) {
                        a.unlock();
                    }
                    if (b.isHeldByCurrentThread()) {
                        b.unlock();
                    }


                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    b.tryLock(5, TimeUnit.SECONDS);
                    System.out.println(Thread.currentThread().getName() + "尝试获取b 成功");
                    System.out.println(Thread.currentThread().getName() + "尝试获取a ...");
                    a.tryLock(5, TimeUnit.SECONDS);
                    System.out.println(Thread.currentThread().getName() + "尝试获取b 成功");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    if (a.isHeldByCurrentThread()) {
                        a.unlock();
                    }
                    if (b.isHeldByCurrentThread()) {
                        b.unlock();
                    }
                }
            }
        });

        t1.start();
        t2.start();

    }
}
